package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/client/httplib"
	"github.com/beego/beego/v2/core/validation"
	"github.com/ethereum/go-ethereum/log"
	"github.com/google/uuid"
	"photo_credit/constant"
	"photo_credit/constant/http"
	"photo_credit/logic"
	"photo_credit/models"
	"photo_credit/utils"
	"strings"
)

type UserController struct {
	MainController
}

var service = logic.UserService{}

// Login 登录
func (c *UserController) Login() {

	id, _ := c.GetInt64("id")
	password := c.GetString("password")

	user := models.User{Id: id, Password: password}
	reuslt := models.User{}
	var err error
	reuslt, err = service.Login(user)
	fmt.Println(reuslt)
	if err != nil {
		c.Data["result"] = "登录失败" + err.Error()
		c.TplName = "login.html"
	} else {
		//设置session
		c.SetSession(constant.USER_SESSION, reuslt)
		c.Data[constant.USER_SESSION] = reuslt
		c.TplName = "index.html"
	}
	//c.APIReturn(http.SUCCESS, "登录成功", nil)

}

// Logout 注销
func (c *UserController) Logout() {
	c.SetSession(constant.USER_SESSION, nil)
	c.TplName = "index.html"
}

// GetSessionValue
// 获取用户登录session
func (c *UserController) GetSessionValue() {
	user := c.GetSession(constant.USER_SESSION)
	user = user.(models.User)
	c.APIReturn(http.SUCCESS, "登录成功", user)
}

// Post
// 用户注册
// @router / [post]
func (c *UserController) Post() {
	//数据验证器全局变量
	var valid = validation.Validation{}
	user := new(models.User)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		log.Error(err.Error())
	}

	//数据验证
	b, err := valid.Valid(*user)
	if !b {
		// validation does not pass
		for _, err := range valid.Errors {
			c.APIReturn(20001, "数据校验不通过", err)
		}
	}

	models.AddUser(user)
	c.APIReturn(200, "成功", nil)
}

// UploadIdentityCard
// 上传身份证并解析到用户表中
// @router /identity [post]
func (c *UserController) UploadIdentityCard() {
	//curl -i -X POST https://personcard.market.alicloudapi.com/ai-market/ocr/personid'  -H 'Authorization:APPCODE 你自己的AppCode' --data 'AI_IDCARD_IMAGE=%E8%BA%AB%E4%BB%BD%E8%AF%81%E5%9B%BE%E5%83%8F&AI_IDCARD_IMAGE_TYPE=%E8%BA%AB%E4%BB%BD%E8%AF%81%E5%9B%BE%E5%83%8F%E7%B1%BB%E5%9E%8B&AI_IDCARD_SIDE=%E8%BA%AB%E4%BB%BD%E8%AF%81%E6%AD%A3%E5%8F%8D%E9%9D%A2'
	f, f2, err := c.GetFile("file")
	defer f.Close()
	//获取文件失败
	if err != nil {
		c.APIReturn(20001, "文件上传失败", err)
	}
	//打印文件后缀 todo
	fmt.Println(strings.Split(f2.Filename, ".")[1])
	//读取文件
	buffer := make([]byte, 500000)
	f.Read(buffer)
	newUUID, _ := uuid.NewUUID()
	card_url := utils.UploadIdCard(buffer, newUUID.String()+"."+strings.Split(f2.Filename, ".")[1])
	fmt.Println(card_url)

	//调用接口，解析身份证
	req := httplib.Post("https://personcard.market.alicloudapi.com/ai-market/ocr/personid")
	req.Header("Authorization", "APPCODE 7a04b24265214145a809643d23a0e471")
	req.Param("AI_IDCARD_IMAGE_TYPE", "1")
	req.Param("AI_IDCARD_SIDE", "FRONT")
	req.Param("AI_IDCARD_IMAGE", card_url)
	result, err := req.String()
	if err != nil {
		return
	}
	fmt.Println("response:", result)

	//解析身份证到数据库中
	var resultMap map[string]map[string]interface{}
	json.Unmarshal([]byte(result), &resultMap)
	fmt.Println("#################################")
	for k, v := range resultMap {
		fmt.Println(k, ":", v)
	}

	//获取身份证
	sfz := resultMap["PERSON_ID_ENTITY"]["PERSON_ID"].(string)
	//获取登录后的用户id
	session := c.GetSession(constant.USER_SESSION)
	user := session.(models.User)
	user.IdentityCard = sfz
	//更新到数据库
	models.UpdateUser(&user)

	c.APIReturn(200, "上传成功", "请核对您的身份证号码："+user.IdentityCard)
}
